package com.kaka.bus.engine.borrow.idcard;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.kaka.bus.AppCenter;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.IDCardFrontBean;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.di.DataManager;
import com.kaka.bus.engine.RouterUtil;
import com.kaka.bus.engine.common.impl.LoanService;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.mvp.RxPresenter;
import com.kaka.bus.util.Base64En;
import com.kaka.bus.util.U;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zhangqi on 2016/10/19.
 * e-mail : ${email}
 * desc :
 */

public class IdCardPresenter extends RxPresenter<IdCardContract.View> implements IdCardContract.Presenter {

    private byte[] mPortraitData;
    private LoanService mLoanService;
    @Inject
    AppCenter mAppCenter;

    @Inject
    public IdCardPresenter(DataManager dataManager,LoanService loanService) {
        super(dataManager);
        mLoanService = loanService;
        setService(mLoanService);
    }

    @Override
    public void sendPic(int resultCode, Intent data, int frontOrBack,String userId,String token) {
        if (resultCode == RESULT_OK) {
            byte[] frontBytes = data.getByteArrayExtra("idcardImg");
            if(frontOrBack == 103){
                mPortraitData = data.getByteArrayExtra("portraitImg");
                readIdCardInfo(frontBytes,mPortraitData,userId,token);
            }else if(frontOrBack == 104){
                readIdCardInfo(frontBytes,null,userId,token);
            }
        }else{
            mView.showMessage("取消");
        }
    }

    @Override
    public void sendService(String userId,String token, IDCardFrontBean idCard, String photo, int type) {
        if(idCard == null){
            mView.sendFailed(UserConstant.IDCARD_UNKNOW);
            return;
        }
        Map<String,String> map = new HashMap<>();
        if(type == 103){
            String strDate = idCard.getBirthday().toString();
            map.put(Constant.USERID,userId);
            map.put("card_num",idCard.getId_card_number());
            map.put("name",idCard.getName());
            map.put("sex",idCard.getGender());
            map.put("nation",idCard.getRace());
            map.put("birthday",strDate);
            map.put("address",idCard.getAddress());
            map.put("card_byte",photo);
            map.put("head_byte", new String(Base64En.base64Encode(mPortraitData)));
            map.put("description","没有说明");
            mView.showDialog("提交身份证信息中...");
            addSubscribe(mDataManager
                    .getApi()
                    .commitIdcardz(map,token)
                    .compose(T.D())
                    .subscribeWith(new Result<HttpWrapper<String>>() {
                        @Override
                        protected void onSuccess(HttpWrapper<String> bean) {
                            mView.sendSuccess(bean);
                        }

                        @Override
                        protected void onFinish() {
                            mView.dissDialog();
                        }
                    }));
        }else if(104 == type){
            String vaild_priod = idCard.getValid_date();
            if(vaild_priod == null){
                mView.sendFailed(0);
                return;
            }
            String[] split = vaild_priod.split("-");
            String start_date = split[0].replace(".", "-");

            String end_date = "长期";
            if(!TextUtils.isEmpty(split[1])){
                end_date = split[1].replace(".", "-");
            }

            map.put(Constant.USERID,userId);
            map.put("office",idCard.getIssued_by());
            map.put("start_date",start_date);
            map.put("end_date",end_date);
            map.put("card_byte", photo);
            map.put("description","没有说明");
            mView.showDialog("身份证信息提交中...");

            addSubscribe(mDataManager
                    .getApi()
                    .commitIdcardf(map,token)
                    .compose(T.D())
                    .subscribeWith(new Result<HttpWrapper<String>>() {
                        @Override
                        protected void onSuccess(HttpWrapper<String> bean) {
                            mView.sendSuccess(bean);
                        }

                        @Override
                        protected void onFinish() {
                            mView.dissDialog();
                        }
                    }));
        }
    }

    private void readIdCardInfo(byte[] frontBytes, byte[] portraitData,String userId,String token) {

        Map<String, RequestBody> map = new HashMap<>();
        map.put("card"+"\"; filename=\""+"card.png", RequestBody.create(MediaType.parse("image/png"),frontBytes));
        if(portraitData != null){
            map.put("head"+"\"; filename=\""+"head.png", RequestBody.create(MediaType.parse("image/png"),portraitData));
        }
        mView.showDialog("身份证扫描中...");

        addSubscribe(mDataManager
                .getApi()
                .readIdCardInfo(userId,token, U.Sign(userId,token),map)
                .compose(T.D())
                .subscribeWith(new Result<HttpWrapper<IDCardFrontBean>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<IDCardFrontBean> bean) {
                        if(Constant.SUCCESS_CODE.equals(bean.getCode())){
                            mView.setInfo(frontBytes,bean.getData());
                        }else if(Constant.ERROR_CODE.equals(bean.getCode())){
                            if("202".equals(bean.code)){
                                /**
                                 * 重新拍摄照片
                                 */
                                mView.reTakePhoto();
                            }else{
                                mView.showMessage(bean.getInfo());
                            }
                        }else{
                            mView.showMessage(bean.getInfo());
                            mView.reTakePhoto();
                        }
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        mView.dissDialog();
                    }
                }));
    }

    @Override
    public void uploadContact(String userId, String json) {
        mLoanService.uploadContact(userId, json, new Result<HttpWrapper<String>>() {
            @Override
            protected void onSuccess(HttpWrapper<String> s) {
                mView.uploadContactSuccess(s);
            }

            @Override
            protected void onFaild() {
                super.onFaild();
                mView.uploadContactFaild();
            }
        });
    }

    @Override
    public void router(Activity activity) {
        mView.showDialog("查询节点中...");
        RouterUtil.router(activity, mDataManager.getApi(),mCompositeDisposable, () -> {
            if(mView != null){
                mView.dissDialog();
            }
        });
    }
}
